package cn.huihuo.weibo.service;

import cn.huihuo.weibo.module.*;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Dan
 * Created by zhengjunbo on 2015/11/9.
 */
public class ProductHotService {
    public static final ProductHotService service = new  ProductHotService();

    /**
     * 商品热度添加
     */
    public void processProductHot(){
        List<Product> products = Product.product.find("select * from product");
        for(Product product:products){
            statisticalProductHot(product.getInt("id"));
        }
    }


    /**
     * 统计商品热度
     * 1、原创ugc
     * 2、评论
     * 3、原创ugc中所有点赞数量相加。填充到product hot中去。
     * @param productId
     */
    public void statisticalProductHot(Integer productId){
        ProdComment ugcSize = ProdComment.prodComment.prodUgcSize(productId);//ugc总数
        ProdComment commentSize = ProdComment.prodComment.prodCommentSize(productId);
        ProdComment channelBillSize = ProdComment.prodComment.prodChannelBillSize(productId);//投票总数

        double hotWeight = ugcSize.getLong("size")*3 + commentSize.getLong("size") + channelBillSize.getBigDecimal("size").multiply(new BigDecimal("0.5")).doubleValue();



        //统计人数，互动总数,先统计ugc的总数，再统计对应用户总数。再统计评论中的总数，和用户数。再统计点赞数。互动数=ugc数+评论数+点赞数，人数=操作的用户数量
        Set<String> totalUser = new HashSet<>();
        List<ProdComment> prodComments = ProdComment.prodComment.findByProdId(productId);

        Integer totalSize = prodComments.size();

        for(ProdComment prodComment:prodComments){
            String userId = prodComment.getStr("user_id");
            totalUser.add(userId);

            Integer ugcId = prodComment.getInt("id");
            List<Comment> comments = Comment.comment.findCommentByUGCId(String.valueOf(ugcId));
            for(Comment comment:comments){
                String commentUserId = comment.getStr("user_id");
                totalUser.add(commentUserId);
            }
            totalSize = totalSize+comments.size();

            List<UserChooseChannel> userChooseChannel = UserChooseChannel.dao.getUserChooseChannel(ugcId);
            for(UserChooseChannel userChooseChannel1:userChooseChannel){
                String channelUserId = userChooseChannel1.getStr("user_id");
                totalUser.add(channelUserId);
            }
            totalSize = totalSize+userChooseChannel.size();
        }


        ProductHot productHot = ProductHot.dao.findByProdId(productId);
        if(productHot == null){
            productHot = new ProductHot();
            productHot.set("prod_id",productId).set("hot_weight",hotWeight).set("interaction", totalSize).set("interaction_user",totalUser.size()).save();
        } else { //update
            productHot.set("hot_weight",hotWeight).set("interaction",totalSize).set("interaction_user",totalUser.size()).update();
        }


    }
}
